﻿import MyTree.TreeNode;
dynamic class MyTree.TreeOrganize{
	public static function OrganizeToTree(nodeArray:Array,idname:String,fatherIdname:String):TreeNode
	{
		var arr:Array=new Array();
		for(var i=0;i<nodeArray.length;i++){
			arr[i]=nodeArray[i];
		}
		var loopTimes=2000;
		var timessssss=loopTimes;
		while(arr.length>1 && timessssss-->0){
			//trace("------- "+arr.length+" ------");
			var nd=arr.pop();
			var finded:Boolean=false;
		//	trace("nd=("+nd[idname]+") 's fatherid=("+nd[fatherIdname]+")");
			//trace("start find child......")
			for(var i=0;i<arr.length;i++){
				//trace("check::("+arr[i][idname]+") 's fatherid=("+arr[i][fatherIdname]+") | "+nd[idname])
				if(arr[i][fatherIdname]==nd[idname] && !finded){
					trace("find id=("+arr[i][idname]+")")
					if(nd.AddChild==undefined){
						if(nd.child==undefined){
							nd.child=new Array();
						}
						nd.child.push(arr[i]);
					}else{
						nd.AddChild(arr[i]);
					}
					arr[i]=nd;
					finded=true;
					//break;
				}
			}
			//trace("start find father......")
			if(!finded){
				for(var i=0;i<arr.length;i++){
					var fnd:TreeNode=findedNodeInSubNodes(arr[i],idname,nd[fatherIdname]);
					if(fnd!=null){
						if(fnd.AddChild==undefined){
							if(fnd.child==undefined){
								fnd.child=new Array();
							}
							fnd.child.push(nd);
						}else{
							fnd.AddChild(nd);
						}
						break;
					}
				}
			}
			if(timessssss==1 && arr.length>2){
				trace("**警告**在"+loopTimes+"次内未能完成PathTree的整理动作！显示可能有错！");
			}
		}
		return arr[0];
	}
	public static function findedNodeInSubNodes(node:TreeNode,idToFindName:String,idToFindValue:Object):TreeNode{
		if(node[idToFindName]==idToFindValue){
			//trace("fined father");
			return node;
		}
		for(var i=0;i<node.Child.length;i++){
			var nd:TreeNode=findedNodeInSubNodes(node.Child[i],idToFindName,idToFindValue);
			if(nd!=null){
				return nd;
			}
		}
		return null;
	}
}



